/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servidormemory;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.UnknownHostException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author DAM110
 */
public class VentanaPrincipal extends javax.swing.JFrame {    
    
    private Servidor s;
    private int puerto = 6000;
    
    public VentanaPrincipal() {
        
        GestionarEstado.setVp(this);
        GuardarPuntuacion.iniciarGuardado();
        GuardarPuntuacion.recuperarNombresObject();
        actualizarHora();
        
        initComponents();    
        this.setLocationRelativeTo(null);   
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT
     * modify this code. The content of this method is always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        pTab = new javax.swing.JTabbedPane();
        pAjustes = new javax.swing.JPanel();
        bIniciar = new javax.swing.JButton();
        bParar = new javax.swing.JButton();
        bEscribir = new javax.swing.JButton();
        bPuerto = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        lEstado = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        lEscrito = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        lPuerto = new javax.swing.JLabel();
        lHora = new javax.swing.JLabel();
        bReiniciar = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        pPrincipal = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabla = new javax.swing.JTable();

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        bIniciar.setText("Iniciar");
        bIniciar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bIniciarActionPerformed(evt);
            }
        });

        bParar.setText("Parar");
        bParar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bPararActionPerformed(evt);
            }
        });

        bEscribir.setText("Escribir forzoso");
        bEscribir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bEscribirActionPerformed(evt);
            }
        });

        bPuerto.setText("Cambiar Puerto");
        bPuerto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bPuertoActionPerformed(evt);
            }
        });

        jLabel1.setText("Estado:");

        lEstado.setText(" ");

        jLabel2.setText("Estado:");

        lEscrito.setText("  ");

        jLabel3.setText("El puerto por defecto es el: 6000. Tiene que ser mayor de 6000.");

        lPuerto.setText("Puerto actual: 6000.");

        lHora.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lHora.setText(" ");

        bReiniciar.setText("Reiniciar puntuaciones");
        bReiniciar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bReiniciarActionPerformed(evt);
            }
        });

        jLabel4.setText("¡Mucha precaución!");

        javax.swing.GroupLayout pAjustesLayout = new javax.swing.GroupLayout(pAjustes);
        pAjustes.setLayout(pAjustesLayout);
        pAjustesLayout.setHorizontalGroup(
            pAjustesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pAjustesLayout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addGroup(pAjustesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pAjustesLayout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pAjustesLayout.createSequentialGroup()
                        .addGroup(pAjustesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lHora, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(pAjustesLayout.createSequentialGroup()
                                .addGroup(pAjustesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(pAjustesLayout.createSequentialGroup()
                                        .addComponent(jLabel2)
                                        .addGap(18, 18, 18)
                                        .addComponent(lEscrito, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addGap(29, 29, 29))
                                    .addGroup(pAjustesLayout.createSequentialGroup()
                                        .addComponent(lPuerto)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .addGroup(pAjustesLayout.createSequentialGroup()
                                        .addGap(0, 0, Short.MAX_VALUE)
                                        .addComponent(jLabel1)
                                        .addGap(18, 18, 18)
                                        .addComponent(lEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(36, 36, 36)))
                                .addGroup(pAjustesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(bPuerto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(bEscribir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addGroup(pAjustesLayout.createSequentialGroup()
                                        .addComponent(bIniciar)
                                        .addGap(28, 28, 28)
                                        .addComponent(bParar))))
                            .addGroup(pAjustesLayout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(bReiniciar)))
                        .addGap(38, 38, 38))))
        );
        pAjustesLayout.setVerticalGroup(
            pAjustesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pAjustesLayout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addGroup(pAjustesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bIniciar)
                    .addComponent(bParar)
                    .addComponent(jLabel1)
                    .addComponent(lEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(pAjustesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bEscribir)
                    .addComponent(jLabel2)
                    .addComponent(lEscrito))
                .addGap(31, 31, 31)
                .addComponent(jLabel3)
                .addGap(30, 30, 30)
                .addGroup(pAjustesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(bPuerto)
                    .addComponent(lPuerto))
                .addGap(33, 33, 33)
                .addGroup(pAjustesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bReiniciar)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
                .addComponent(lHora)
                .addGap(24, 24, 24))
        );

        pTab.addTab("Ajustes", pAjustes);

        pPrincipal.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                pPrincipalComponentShown(evt);
            }
        });

        tabla.setModel(new Modelo(GuardarPuntuacion.getGlobal()));
        jScrollPane1.setViewportView(tabla);

        javax.swing.GroupLayout pPrincipalLayout = new javax.swing.GroupLayout(pPrincipal);
        pPrincipal.setLayout(pPrincipalLayout);
        pPrincipalLayout.setHorizontalGroup(
            pPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 468, Short.MAX_VALUE)
        );
        pPrincipalLayout.setVerticalGroup(
            pPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 324, Short.MAX_VALUE)
        );

        pTab.addTab("Principal", pPrincipal);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pTab)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pTab)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bIniciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bIniciarActionPerformed
        
       
       s = new Servidor(puerto);
       s.start();
       lEstado.setText("Iniciado");
       
    }//GEN-LAST:event_bIniciarActionPerformed

    private void pPrincipalComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_pPrincipalComponentShown
        
        tabla.setModel(new Modelo(GuardarPuntuacion.getGlobal()));
    }//GEN-LAST:event_pPrincipalComponentShown

    private void bPararActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bPararActionPerformed
        
        pararServidor();    
       
        while(!s.finalizado() && s.isContinuar()){
        
        }
    }//GEN-LAST:event_bPararActionPerformed

    private void bEscribirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bEscribirActionPerformed
        
        GuardarPuntuacion.guardarNombresObject(GuardarPuntuacion.getGlobal());
        lEscrito.setText("Escritura existosa");
    }//GEN-LAST:event_bEscribirActionPerformed

    private void bPuertoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bPuertoActionPerformed
        
        int p = Integer.parseInt(JOptionPane.showInputDialog("Escribe el número del nuevo puerto"));
        if(p != puerto){
        puerto = (p > 6000) ? p : puerto;  
            
        pararServidor(); 
        s = new Servidor(puerto);
        s.start();        
        lPuerto.setText("Puerto actual: " + puerto + ".");
        }
    }//GEN-LAST:event_bPuertoActionPerformed

    private void bReiniciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bReiniciarActionPerformed
        
        int booleano = JOptionPane.showConfirmDialog(this, "¿Estás completamente seguro?", "Reiniciar", JOptionPane.YES_NO_OPTION);
        if(booleano == JOptionPane.YES_OPTION){
            
            GuardarPuntuacion.reiniciarPuntuacion();
        }else{
            
            JOptionPane.showMessageDialog(this, "No se reinició");
        }
    }//GEN-LAST:event_bReiniciarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                
                new VentanaPrincipal().setVisible(true);
            }
        });
    }
    
    private void pararServidor(){
        
        if(s != null && s.isContinuar()){
        s.setContinuar(false);
        try {
            
            java.net.Socket clienteFalso = new java.net.Socket("127.0.0.1",s.servidor.getLocalPort());
            clienteFalso.close();
            
        } catch (UnknownHostException ex) {
            Logger.getLogger(VentanaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(VentanaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
        }
        }
    }
    
    public void setlEscrito(String nuevo) {
        
        this.lEscrito.setText(nuevo);
    }

    public void setlEstado(String nuevo) {
        this.lEstado.setText(nuevo);
    }

    public void setlPuerto(String nuevo) {
        this.lPuerto.setText(nuevo);
    }
    
    private void actualizarHora(){
        
        
        final Format f = new SimpleDateFormat("HH:mm:ss");
        ActionListener al = new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                
                java.util.Date fecha = new java.util.Date();
                lHora.setText(fecha.toString());
            }           
        };
        
        javax.swing.Timer t = new javax.swing.Timer(1000,al);
        t.start();
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bEscribir;
    private javax.swing.JButton bIniciar;
    private javax.swing.JButton bParar;
    private javax.swing.JButton bPuerto;
    private javax.swing.JButton bReiniciar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lEscrito;
    private javax.swing.JLabel lEstado;
    private javax.swing.JLabel lHora;
    private javax.swing.JLabel lPuerto;
    private javax.swing.JPanel pAjustes;
    private javax.swing.JPanel pPrincipal;
    private javax.swing.JTabbedPane pTab;
    private javax.swing.JTable tabla;
    // End of variables declaration//GEN-END:variables
}
